<template>
	<view class="bg-light">
		<tabsTop tabName="合美供销云平台"></tabsTop>
		<scroll-view scroll-y="true" class="scroll-Y" @scrolltolower="shop_scroll">
			<view class="search">
				<mySearch class="searchClick" @click="searchClick()"></mySearch>
			</view>
			<!-- 	<view class="h3 flex justify-between align-center px-2 bg-white"
				style="height: 100rpx;border-left: 10rpx solid green;">
				导航紧挨着的标题
				<text class="font-lg">{{Column_Name}}</text>
				<view style="width: 60rpx;height: 78rpx;">
					<image :src="Domain_ICON+'/fire.png'" alt="" mode="aspectFit" class="img"></image>
				</view>
			</view> -->
			<!-- 商品列表模块 -->
			<view class="product-list px-3 pt-1" v-if="goods.length>0">
				<view class="sign_row flex flex-wrap" :class="screenWidth<480?'justify-between':''">
					<!-- 循环生成两个商品数据 -->
					<view class="bg-white mb-3 rounded-lg overflow-hidden" v-for="(item,index) in goods" :key="index"
						style="width: 330rpx;" :style="screenWidth>480?'margin-left: 0.15%;':''"
						@click="productClick(item.Article_Name,item.Article_SerialNumber,item.Sales_Unit_Price_SerialNumber,item.Store_SerialNumber,item.ShopColumn_Id)">
						<view class="w-100" style="height: 350rpx;">
							<image :src="Domain_IMG+item.Picture_URL " :alt="item.Article_serialNumber " class="img">
							</image>
						</view>
						<view class="px-2">
							<!-- 这行根据数据显示人气第几 -->
							<view class="flex justify-between flex-column py-3">
								<!-- 商品名 -->
								<view class="font-sm" style="height: 50rpx;">
									<text class="text-ellipsis-2">{{item.Article_Name}}</text> 
								</view>
								<view class="flex justify-between mt-3">
									<!-- 商品价格 -->
									<view class="flex align-center align-center">
										<money :money="item.Sales_Unit_Price"></money>
									</view>
									<!-- 购物车-->
									<view style="width: 40rpx; height: 40rpx;" @click.stop="shopCart(item)">
										<image :src="Domain_ICON+'/shopcart.png'" mode="" class="img" style=""></image>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<!-- 购物车弹窗 -->
		<popUp type="top" bgColor="#fff" :show='shopcart' @Close="()=>{shopcart=false}" Height="70">
			<view class="shopcart flex ml-3" style="width: 70%;">
				<view class="getValue" :data-Article_SerialNumber="good.Article_SerialNumber"
					:data-quantity="good.quantity"
					:data-Unit_Price="good.specifications[0]?good.specifications[0].Unit_Price:''">
				</view>
				<!-- <view class="get_samevalue"
						:data-Sales_Unit_Price_Stock_SerialNumber="good.Sales_Unit_Price_Stock_SerialNumber">
			
					</view> -->
				<view class="py-3" style="width:270rpx;height: 270rpx;">
					<image :src="Domain_IMG+good.Picture_URL" mode="aspectFit" class="img"></image>
				</view>
				<!-- 商品规格只有一个时 -->
				<view class="ml-2 flex flex-column justify-end pb-4" style="width: 200rpx;"
					v-if="good.hasOwnProperty('specifications')&&good.specifications.length==1">
					<money :money="good.specifications[0].Sales_Unit_Price"></money>
					<view class="font-sm" style="color: #ccc;">
						<text>剩余{{good.specifications[0].Stock_Remain}}件</text>
					</view>
				</view>
				<!-- 商品规格大于一个时 -->
				<view class="ml-2 flex flex-column justify-end pb-4" style="width: 200rpx;"
					v-if="good.hasOwnProperty('specifications')&&good.specifications.length>1">
					<!-- 未选中时显示 -->
					<view class="" v-if="JSON.stringify(selectSpe)=='{}'">
						<view class="flex">
							<money :money="minPrice"></money>-
							<money :money="maxPrice"></money>
						</view>

						<view class="font-sm" style="color: #ccc;">
							<text>剩余{{totalRemain}}件</text>
						</view>
						<view class="font-sm" style="color: #ccc;">
							<text>请选择 购买规格</text>
						</view>
					</view>
					<!-- 选中时显示 -->
					<view class="" v-else>
						<money :money="selectSpe.Sales_Unit_Price"></money>
						<view class="font-sm" style="color: #ccc;">
							<text>剩余{{selectSpe?selectSpe.Stock_Remain:''}}件</text>
						</view>
						<view class="font-sm" style="color: #ccc;">
							<text>已选 {{selectSpe.Specifications_Name}}</text>
						</view>
					</view>
				</view>
			</view>
			<view class="flex flex-column mx-3" v-if="good.specifications.length>1">
				<view class="">
					购买规格
				</view>
				<view class="flex">
					<view class="mr-2 rounded-lg flex justify-center align-center" :class="{'speActive':item.isSelect}"
						@click="speClick(item,index)" v-for="(item,index) in good.specifications" :key="index"
						style="background-color: rgb(247,248,250);width: 130rpx;height: 60rpx;">
						<view>
							{{item.Specifications_Name}}
						</view>
					</view>
				</view>
			</view>
			<view class="flex justify-between mx-3 mt-3">
				<view class="font">购买数量</view>
				<view class="">
					<counter :num="good.quantity"
						:max="Number(good.specifications[0]?good.specifications[0].Stock_Remain:'')"
						@Count="counterClick">
					</counter>
				</view>
			</view>
			<view class="shop-cart position-fixed flex justify-center font text-white "
				style=" bottom:20rpx; margin:0 auto">
				<button class="btn-left text-white" :disabled="loading" @click="addCart()">加入购物车</button>
				<button class="btn-right text-white" @click="buyNow()">立即购买</button>
			</view>
		</popUp>
		<!-- <botSponsor></botSponsor> -->
		<!-- <tabsBottom></tabsBottom> -->
	</view>
</template>

<script>
	const app = getApp();
	import tabsTop from "@/components/tabs/tabs-top.vue";
	import tabsBottom from "@/components/tabs/tabs-bottom.vue";
	import botSponsor from "@/components/botsponsor/sponsor.vue"
	import popUp from "@/components/tabs/pop-up.vue"
	import {
		getHMGXLocation,
		getHMGXGoods
	} from "@/api/index.js"
	import mySearch from "@/components/mysearch/mysearch.vue"
	import {
		getColumnConfig,
		getWX2GoodsIdAction,
		getWX3GoodsIdAction
	} from "@/api/index.js"
	import money from "@/components/tool/money.vue"
	import counter from "@/components/tool/counter.vue"
	import {
		getAddAction
	} from "@/api/global.js"
	import {
		getWXCheckShopCarAction,
		editWXEditShopCarQuantity,
		getWX4GoodsIdAction
	} from "@/api/article.js"
	import {
		NowTime
	} from "@/static/js/DateUtil.js"
	import {
		accMul
	} from "@/static/js/GeneralUtil.js"
	export default {
		components: { //轮播图组件
			tabsTop,
			tabsBottom,
			botSponsor,
			mySearch,
			popUp,
			money,
			counter
		},
		data() {
			return {
				Domain_ICON: app.globalData.Domain_ICON,
				Domain_IMG: app.globalData.Domain_IMG,
				goods: [], //  多种商品
				good: {
					specifications: []
				}, // 点击单个商品获取商品信息
				selectIndex: '', //当前选中商品的索引
				totalRemain: 0, // 未选中时所有商品的总剩余   
				minPrice: 0, // 规格中价格最小
				maxPrice: 0, // 规格中价格最大
				selectSpe: {}, // 选中的规格
				shopcart: false,
				loading: false,
				Column_Name: '',
				screenWidth: uni.getSystemInfoSync().windowWidth,
				good_form: {
					ShopColumn_Id: '',
					Open_ID: app.globalData.Open_ID,
					page: 1,
					limit: 20,
					Article_Name: '',
					Category_SerialNumber: '',
					Enterprise_Info_SerialNumber: app.globalData.Enterprise_Info_SerialNumber
				},
				ShopColumn_Id: '',
			}
		},
		onLoad(option) {
			if (option.Column_Id) {
				this.ShopColumn_Id=option.Column_Id
				this.good_form.ShopColumn_Id=option.Column_Id
				this.getWX3GoodsIdAction(option.Column_Id)
			}
		},
		methods: {
			// 滚动底部加载商品
			shop_scroll() {
				//console.log(123);
				if (this.goods.length <= 50) {
					this.getWX3GoodsIdAction()
					uni.showToast({
						title: "正在加载商品",
						icon: "loading",
						duration: 1500
					})
				} else {
					uni.showToast({
						title: "已加载全部商品",
						duration: 1500
					})
				}
			},
			// 获取商品
			async getWX3GoodsIdAction() {
				const res = await getWX3GoodsIdAction(this.good_form)
				this.good_form.page++
				if (res.Status == "success") {
					res.tableData.forEach((item, index) => {
						this.goods.push(item)
					})
				}
				//console.log(res);
			},
			// 点击商品,进入商品详情页
			productClick(name, Article_SerialNumber, Sales_Unit_Price_SerialNumber, Store_SerialNumber, ShopColumn_Id) {
				if (app.globalData.isPC) {
					window.location.href =app.globalData.Domain_Url+ `#/pages/detail/supply-detail?id=${encodeURIComponent(
						Article_SerialNumber)}&ShopColumn_Id=${encodeURIComponent(ShopColumn_Id)}&shop_good=${"shop_good"}`
				} else {
					uni.navigateTo({
						url: "/pages/index/productDetails?name=" + name + "&Article_SerialNumber=" +
							Article_SerialNumber + "&Sales_Unit_Price_SerialNumber=" +
							Sales_Unit_Price_SerialNumber +
							"&Store_SerialNumber=" + Store_SerialNumber + '&ShopColumn_Id=' + ShopColumn_Id
					})
				}
			},
			provinceClick(name, index) {
				uni.navigateTo({
					url: "/pages/index/manygoods"
				})
			},
			// 点击购物车图标，出现购物车弹窗

			async shopCart(item) {
				if (app.globalData.isPC) {
					// https://marketing.ediblefungus.cn/dist/h5XKLJ/index.html/
					// http://localhost:8080/dist/h5XKLJ/
						// if(this.screenWidth < 480){
					window.location.href =app.globalData.Domain_Url+ `#/pages/detail/supply-detail?id=${encodeURIComponent(
						item.Article_SerialNumber)}&ShopColumn_Id=${encodeURIComponent(item.ShopColumn_Id)}&shop_good=${"shop_good"}`
				}else{
					this.totalRemain = 0;
					this.loading = false;
					this.good = {
						...item
					}
					const res = await getWX4GoodsIdAction({
						ShopColumn_Id: item.ShopColumn_Id,
						Article_SerialNumber: item.Article_SerialNumber,
						Enterprise_Info_SerialNumber: item.Enterprise_Info_SerialNumber,
						Open_ID: app.globalData.Open_ID
					})
					// if(res.Data[0].hasOwnProperty('Children')){
					// 	this.good.specifications.forEach((item,index)=>{
					// 		this.good.specifications[index].Children={
					// 			Gifts:[],
					// 		}
					// 		this.good.specifications[index].Children.Gifts=res.Data[index].Children.Gifts
						
					// 	})
					// }
					//console.log('加入购物车', item)
					this.$set(this.good, "specifications", res.Data)
					this.$set(this.good, "quantity", 1)
					//console.log(this.good, '商品信息');
					this.minPrice = res.Data[0].Sales_Unit_Price
					this.maxPrice = res.Data[0].Sales_Unit_Price
					this.good.specifications.forEach((item, index) => {
						item.isSelect = false;
						this.totalRemain += item.Stock_Remain * 1;
						if (item.Sales_Unit_Price > this.maxPrice) {
							this.maxPrice = item.Sales_Unit_Price
						}
						if (item.Sales_Unit_Price < this.minPrice) {
							this.minPrice = item.Sales_Unit_Price
						}
					})
					// 传入需要拿到数据的选择器
					// this.getvalues('.getValue');
					this.shopcart = !this.shopcart;
				}
			},
			// 购物车弹窗计数器
			counterClick(e) {
				this.good.quantity = e;
			},
			// 立即购买
			// 购物车中立即购买
			buyNow() {
				if (this.good.specifications.length > 1) {
					if (Object.keys(this.selectSpe).length <= 0) {
						uni.showToast({
							title: '请选择规格',
							icon: "error",
							duration: 1200
						})
						return;
					}
				} else {
					this.selectIndex = 0
				}
				if (this.good.quantity > 0) {

				} else {
					this.good.quantity = 1;
				}
				let Article = {
					Article_Name: this.good.Article_Name,
					Store_SerialNumber: this.good.Store_SerialNumber,
					Category_Name: "普通实物商品",
					Article_SerialNumber: this.good.specifications[this.selectIndex].Article_SerialNumber,
					Picture_URL: this.good.Picture_URL,
					Article_Specifications_SerialNumber: this.good.specifications[this.selectIndex]
						.Article_Specifications_SerialNumber,
					Sales_Unit_Price: this.good.specifications[this.selectIndex].Sales_Unit_Price,
					Sales_Unit_Price_Detail_SerialNumber: this.good.specifications[this.selectIndex].Sales_Unit_Price_Stock_SerialNumber,
					Sales_Unit_Price_Stock_SerialNumber: this.good.specifications[this.selectIndex]
						.Sales_Unit_Price_Detail_SerialNumber,
					Sign: this.good.specifications[this.selectIndex].Sign,
					Stock_Remain: this.good.specifications[this.selectIndex].Stock_Remain,
					Stock_Sell: this.good.specifications[this.selectIndex].Stock_Sell,
					Quantity: this.good.quantity,
					Unit_Price: this.good.specifications[this.selectIndex].Unit_Price,
					Gifts: this.good.specifications[this.selectIndex].Children.Gifts
				}
				//console.log(this.good);
				uni.navigateTo({
					url: "/pages/index/submitOrder?good=" + encodeURIComponent(JSON.stringify([Article]))
				})
			},
			// 判断购物车有无相同商品
			async getWXCheckShopCarAction(Sales_Unit_Price_Stock_SerialNumber,Article_SerialNumber) {
				//console.log(Sales_Unit_Price_Stock_SerialNumber);
				var res = await getWXCheckShopCarAction({
					App_ID: app.globalData.App_ID,
					Open_ID: app.globalData.Open_ID,
					Sales_Unit_Price_Stock_SerialNumber,
					Article_SerialNumber
				})
				return res;
			},
			// 加入购物车
			async addCart() {
				if (this.good.specifications.length > 1) {
					if (Object.keys(this.selectSpe).length <= 0) {
						uni.showToast({
							title: '请选择规格',
							icon: 'error',
							duration: 1200
						})
						return;
					}
				}
				// //console.log(this.good.specifications[0].Sales_Unit_Price_Stock_SerialNumber, '要添加到购物的');
				this.loading = true;
				if (!this.good.quantity) {
					this.good.quantity = 1
				}
				let index = 0;
				this.good.specifications.forEach((item, index1) => {
					if (item.isSelect) {
						//console.log(item, index, '看下都变没变');
						index = index1;
					}
				})
				// //console.log(this.good,'看看index');
				// 根据每个里的isSelect选中状态判断
				let time = new Date().getTime();	
				var sales_order = {
					Sales_Order_SerialNumber: app.globalData.Open_ID + "_" + time,
					Store_SerialNumber: this.good.Store_SerialNumber,
					Sales_Address: '',
					Sales_Contacts: '',
					Sales_Phone: '',
					Sales_Message: '',
					Sales_Date: NowTime(),
					Open_ID: app.globalData.Open_ID,
					App_ID: app.globalData.App_ID,
					Sales_Amount: accMul(this.good.quantity,this.good.specifications[index].Sales_Unit_Price),
					Collection_Amount: 0,
					Delivery_Amount: 0,
					Receive_Type: 0,
					Refund_Type: 0,
					Enterprise_Info_SerialNumber: app.globalData.Enterprise_Info_SerialNumber,
					Row_Status: 8,
					Children: {
						sales_order_detail: [{
							Sales_Order_Detail_SerialNumber: app.globalData.Open_ID + "_" + time+"_001",
							Sales_Order_SerialNumber: app.globalData.Open_ID + "_" + time,
							Sales_Unit_Price_Stock_SerialNumber: this.good.specifications[index]
								.Sales_Unit_Price_Detail_SerialNumber,
							Sales_Unit_Price_Detail_SerialNumber: this.good.specifications[this.selectIndex].Sales_Unit_Price_Stock_SerialNumber,
							Article_SerialNumber: this.good.specifications[index].Article_SerialNumber,
							Article_Specifications_SerialNumber: this.good.specifications[index]
								.Article_Specifications_SerialNumber,
							Sign: this.good.specifications[index].Sign,
							Quantity: this.good.quantity,
							Unit_Price: this.good.specifications[index].Unit_Price,
							Sales_Unit_Price: this.good.specifications[index].Sales_Unit_Price,
							Amount:  accMul(this.good.quantity,this.good.specifications[index].Sales_Unit_Price),
							Row_Status: 8,
							Receive_Type: 0,
							Refund_Type: 0,
							Enterprise_Info_SerialNumber: app.globalData.Enterprise_Info_SerialNumber,
						}]
					}
				}
				// 看下当前商品是否有赠品
				if (this.good.specifications[index].Children.Gifts.length > 0) {
					this.good.specifications[index].Children.Gifts.forEach(item => {
						item.Order_Type = 1
						item.Amount = accMul(item.Quantity, item.Sales_Unit_Price)
					})
					sales_order.Children.sales_order_detail.push(this.good.specifications[index].Children
						.Gifts)
				}
				// //console.log(sales_order,'看看规格变没变');
				var res = await this.getWXCheckShopCarAction(this.good.specifications[index]
					.Sales_Unit_Price_Stock_SerialNumber,this.good.specifications[index]
					.Article_SerialNumber);
				//console.log(res, "查询是否有相同商品");
				if (res.length == 0) {
					// 增加流程
					sales_order.Children.sales_order_detail[0].Amount = accMul(this.good.specifications[index]
						.Sales_Unit_Price, this.good.quantity)
					uni.showLoading({
						title: "加载中...",
					});
					var addres = await getAddAction({
						Data: JSON.stringify({
							sales_order: [sales_order]
						}),
						Open_ID: app.globalData.Open_ID
					})
					uni.hideLoading();
					if (addres.Status == "success") {
						uni.showToast({
							title: '提交成功！',
							icon: 'success'
						})
						const timer = setTimeout(() => {
							clearTimeout(timer)
							this.shopcart = false;
						}, 500)
					} else {
						uni.showToast({
							title: '提交失败！',
							icon: 'error'
						})
					}
				} else {
					uni.showLoading({
						title: "加载中...",
					});
					// 修改购物车商品数量   有问题 修改的不是当前规格的
					var editres = await editWXEditShopCarQuantity({
						Open_ID: app.globalData.Open_ID,
						Article_SerialNumber: res[0].Article_SerialNumber,
						Quantity: this.good.quantity,
						Type: "1"
					})
					uni.hideLoading();
					if (editres.Status == "success") {
						uni.showToast({
							title: '提交成功！',
							icon: 'success'
						})
						const timer = setTimeout(() => {
							clearTimeout(timer)
							this.shopcart = false;
						}, 500)
					} else {
						uni.showToast({
							title: '提交失败！',
							icon: 'error'
						})
					}
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	@media screen and (max-width:480px ) {
		.scroll-Y{
			height: 100vh;
		}
	}
	.shop-cart {
		width: 100%;

		.btn-left {
			padding: 0;
			margin: 0;
			width: 45%;
			border-radius: 0;
			border-top-left-radius: 50rpx;
			border-bottom-left-radius: 50rpx;
			background-color: #383838;
		}

		.btn-right {
			padding: 0;
			margin: 0;
			width: 45%;
			border-radius: 0;
			border-top-right-radius: 50rpx;
			border-bottom-right-radius: 50rpx;
			background-color: #09BB07;
		}
	}
</style>